package com.iddactylogram.server.transfer;

import com.iddactylogram.common.domain.IdConstant;
import com.iddactylogram.server.utils.IPUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;

import java.io.IOException;

public class IdDactylogramBootstrap {
    private final CuratorFramework curatorFramework;
    private final IdDactylogramServer server = new IdDactylogramServer();

    public IdDactylogramBootstrap(CuratorFramework curatorFramework) {
        CuratorFrameworkState state = curatorFramework.getState();
        if (state != CuratorFrameworkState.STARTED) {
            curatorFramework.start();
        }
        this.curatorFramework = curatorFramework.usingNamespace(IdConstant.DEFAULT_ZK_NAMESPACE);
    }

    public IdDactylogramBootstrap(String zkAddress) {
        CuratorFramework temp = CuratorFrameworkFactory.newClient(zkAddress, new RetryNTimes(3, 1000));
        temp.start();
        curatorFramework = temp.usingNamespace(IdConstant.DEFAULT_ZK_NAMESPACE);
    }

    public void run(int port) {
        new Thread(() -> {
            try {
                server.start(port);
            } catch (IOException e) {
                throw new IllegalStateException("IdDactylogramServer 运行错误", e);
            }
        }).start();
        try {
            this.regToZk(port);
        } catch (Exception e) {
            throw new IllegalStateException("IdDactylogramServer 注册到zookeeper失败", e);
        }
    }

    public void stop() {
        server.stop();
        String nodeName = String.format("%s:%s", IPUtils.getIp(), server.getPort());
        try {
            curatorFramework.delete().forPath("/" + nodeName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void regToZk(int port) throws Exception {
        String nodeName = String.format("%s:%s", IPUtils.getIp(), port);
        String path = curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath("/" + nodeName);
        System.out.println(path);
    }


}
